#include <iostream>
#include <cstring>
#include <unistd.h>
#include <arpa/inet.h>
#include <sys/socket.h>
using namespace std;

const char* SERVER_IP = "114.55.137.232"; // 服务器IP地址
const int PORT = 8080;      

int main()
{
    int clientfd=socket(AF_INET,SOCK_STREAM,0);
    if(clientfd<0)
    {
        cerr<<"socket errno"<<endl;
        exit(-1);
    }

    sockaddr_in server;
    memset(&server, 0, sizeof(server));
    server.sin_family=AF_INET;
    server.sin_port=htons(PORT);
    inet_pton(AF_INET,SERVER_IP,&server.sin_addr);

    if(connect(clientfd,(sockaddr*)&server,sizeof(server))<0)
    {
        cerr<<"connect errno"<<endl;
        close(clientfd);
        exit(-1);
    }

    cout << "已连接到服务器 " << SERVER_IP << ":" << PORT << endl;

    while(true)
    {
        char buffer[1024];
        memset(buffer,0,sizeof(buffer));
        cout<<"请输入你想发送的话：";
        string message;
        getline(cin,message);

        if(message=="exit")
        break;

        if(send(clientfd,message.c_str(),message.size(),0)<0)
        cerr<<"send errno"<<endl;
        else
        cout<<"消息成功发送给服务端！"<<endl;

        int sz=recv(clientfd,buffer,sizeof(buffer),0);
        if(sz==0)
        {
            cout<<"服务端断开连接"<<endl;
            break;
        }
        else if(sz>0)
        {
            cout<<"服务端回复: "<<buffer<<endl;
            memset(buffer,0,sizeof(buffer));
        }


    }
    close(clientfd);

    return 0;
}